package com.wl.txcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.wl.txcc.domain.*;
import com.wl.txcc.dto.RedisSmsDto;
import com.wl.txcc.dto.PhoneRegisterDto;
import com.wl.txcc.enums.GlobalErrorCode;
import com.wl.txcc.feign.LoginService;
import com.wl.txcc.mapper.UserMapper;
import com.wl.txcc.result.JSONResult;
import com.wl.txcc.service.ILinkService;
import com.wl.txcc.service.IUserAccountService;
import com.wl.txcc.service.IUserBaseInfoService;
import com.wl.txcc.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wl.txcc.util.AssertUtil;
import com.wl.txcc.constants.CommonConstants;
import com.wl.txcc.util.StrUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author director
 * @since 2022-09-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private LoginService loginService;
    @Autowired
    private IUserBaseInfoService userBaseInfoService;
    @Autowired
    private IUserAccountService userAccountService;
    @Autowired
    private ILinkService linkService;


    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void register(PhoneRegisterDto phoneRegisterDto) {
        //获取前端传递的参数
        String phone = phoneRegisterDto.getMobile();//电话
        Integer regChannel = phoneRegisterDto.getRegChannel();//注册通道
        String pwd = phoneRegisterDto.getPassword();//密码
        String smsCode = phoneRegisterDto.getSmsCode();//短信验证码
        //1.拼接业务建
        String redisKey = String.format(CommonConstants.Register_PHONE_PREFIX, phone);
        //获取redis中的验证码的key
        Object o = redisTemplate.opsForValue().get(redisKey);
        //判断验证码是否为空
        AssertUtil.isNotNull(o, GlobalErrorCode.COMMON_IMAGECODE_NULL);
        //强转验证码
        //RedisSmsDto redisSmsDto = (RedisSmsDto)o;
        String s = o.toString();
        String s1 = s.split(":")[0];
        //判断是否和redis里面的验证码相等
        AssertUtil.isEquals(smsCode,s1,GlobalErrorCode.COMMON_ERRER);
        //查询user表里是否有phone
        User user = selectUser(phone);
        //判断user对象是否为空
        AssertUtil.isNull(user,GlobalErrorCode.USER_IS_NULL_ERROR);
        //保存login信息
        JSONResult jsonResult = saveLogin(phoneRegisterDto);
        //判断是否成功
        AssertUtil.isTrue(jsonResult.isSuccess(),GlobalErrorCode.USER_SAVE_ERROR);
        //判断是否为空
        AssertUtil.isNotNull(jsonResult.getData(),GlobalErrorCode.ERROR);
        //得到id
       Long loginId = Long.valueOf(jsonResult.getData().toString());
       //保存user相关表
        //1.userbiao
        Long userId = saveUser(loginId, phoneRegisterDto);
        //2.t_user_account账户信息表
        insertUserAccount(userId);
        //3.t_user_address基础表
        insertUserBaseInfo(userId,regChannel);


        Link link = new Link();
        String complexRandomString = StrUtils.getComplexRandomString(4);
        link.setCode(complexRandomString);
        link.setUserId(userId);
        linkService.insert(link);

    }

    /**
     *
     * @param id
     */
    @Override
    public String getConnected(Long id) {
        EntityWrapper<Link> objectEntityWrapper = new EntityWrapper<>();
        objectEntityWrapper.eq("user_id",id);
        Link link = linkService.selectOne(objectEntityWrapper);
        String code = link.getCode();
        String prefix = "http://127.0.0.1:6003/reg.phone.html?code="+code;
        return prefix;
    }

    //add表
    private void insertUserBaseInfo(Long userId,Integer regChannel) {
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setId(userId);
        userBaseInfo.setRegChannel(regChannel);
        userBaseInfo.setCreateTime(new Date().getTime());
        userBaseInfoService.insert(userBaseInfo);
    }

    //Account表
    private void insertUserAccount(Long userId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setId(userId);
        userAccount.setCreateTime(new Date().getTime());
        userAccount.setPassword("123456");
        userAccountService.insert(userAccount);
    }
    //user表
    private Long saveUser(Long loginId,PhoneRegisterDto phoneRegisterDto) {
        User user = new User();
        user.setCreateTime(new Date().getTime());
        user.setPhone(phoneRegisterDto.getMobile());
        user.setLoginId(loginId);
        user.setNickName(phoneRegisterDto.getMobile());
        insert(user);
        return user.getId();
    }

    private JSONResult saveLogin(PhoneRegisterDto phoneRegisterDto) {
        //创建对象
        Login login = new Login();
        //设置值
        login.setPassword(phoneRegisterDto.getPassword());
        login.setUsername(phoneRegisterDto.getMobile());
        login.setType(Login.RECEPTION);
        login.setEnabled(Login.ENABLE);
        return loginService.saveOrUpdate(login);
    }

    //查询user
    private User selectUser(String phone) {
        //创建user对象的条件过滤器
        Wrapper<User> wrapper = new EntityWrapper<>();
        //查询phone
        wrapper.eq("phone",phone);
        return selectOne(wrapper);
    }
}
